package com.group2.bankonline.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.group2.bankonline.mapper.AccountMapper;
import com.group2.bankonline.pojo.Account;
import com.group2.bankonline.pojo.Personinfo;
import com.group2.bankonline.pojo.Transrecord;
import com.group2.bankonline.service.IAccountService;
import com.group2.bankonline.service.ITransrecordService;
import com.group2.bankonline.service.impl.AccountServiceImpl;
import com.group2.bankonline.utils.JsonResult;
import com.group2.bankonline.utils.MyJWT;
import com.group2.bankonline.utils.RequestAccountInAndOut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author syf
 * @since 2024-07-11
 */
@RestController
@RequestMapping("/mobilebank/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @Autowired
    private ITransrecordService transrecordService;
    @Autowired
    private AccountMapper accountMapper;

    /*
     * 账户信息不提供修改
     * */

    /*
     * 账户信息显示：（分页显示关联账户信息）
     * 1. 获取前端传来的token
     * 2. 从token中获取用户id
     * 3. 根据id从personinfo、account表中获取需要展示的信息（若在账户表中无信息则提示先绑定账户）
     * */
    @GetMapping("/showaccount")
    public JsonResult showaccount(@RequestParam String token) {
        Personinfo personinfo = MyJWT.getPersonByToken(token);
        int pid = personinfo.getId();
        boolean flag = accountService.havepid(pid);
        if (flag) {
            // 创建分页对象，假设每页大小为3
            Page<Account> page = new Page<>(1, 1);
            // 创建查询条件
            QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("personid", pid);
            // 执行分页查询
            Page<Account> accountPage = accountMapper.selectPage(page, queryWrapper);
            // 获取账户列表
            List<Account> accounts = accountPage.getRecords();
            // 将 Account 对象转换为 Map<String, Object>
            List<Map<String, Object>> accountMaps = accounts.stream().map(account -> {
                Map<String, Object> accountMap = new HashMap<>();
                accountMap.put("id", account.getId());
                accountMap.put("accountname", account.getAccountname());
                accountMap.put("balance", account.getBalance());
                accountMap.put("statusId", account.getStatusid() == 1 ? "正常" : "冻结");
                accountMap.put("personId", account.getPersonid());
                return accountMap;
            }).collect(Collectors.toList());
            return new JsonResult(true, accountMaps);
        } else {
            return new JsonResult(false, "请先绑定账户");
        }
    }

    /*
     * 账户绑定：
     * 1. 获取前端返回用户设置的账户名、密码
     * 2. 从token中获取personinfo中的id
     * 3. 创建账户对象，设置账户属性（账户状态默认为1，存款默认为0）
     * */
    @PostMapping("/bindaccount")
    public JsonResult bindaccount(@RequestParam String token, @RequestBody Account account) {
        Personinfo personinfo = MyJWT.getPersonByToken(token);
        int id = personinfo.getId();
        Account existaccount = accountService.getById(id);
        if (existaccount == null) {
            account.setPersonid(id);
            accountService.bindAccount(account);
            return new JsonResult(true, "账户绑定成功");
        } else {
            return new JsonResult(false, "账户不存在");
        }
    }

    /*
     * 银行卡号查询：
     * 1. 获取前端返回的token
     * 2. 根据token获取用户的personid
     * 3. 查询返回该用户账户所有的银行卡卡号
     * */
    @GetMapping("/getaccountname")
    public JsonResult getaccountname(@RequestParam String token) {
        Personinfo personinfo = MyJWT.getPersonByToken(token);
        int id = personinfo.getId();
        List<Account> accounts = accountService.getaccountname(id);

        // 提取所有卡号
        List<String> accountnames = accounts.stream()
                .map(Account::getAccountname)
                .collect(Collectors.toList());

        Map<String, Object> response = new HashMap<>();
        response.put("accountnames", accountnames);
        return new JsonResult(true, accountnames);
    }


    /*
     * 账户存款取款：
     * 1. 接收前端存取款数据（操作类型转为数据库中的0-存款，1-取款，2-转账）
     * 2. 根据accountid及transtypeid对account表进行修改 （若为取款，金额不得超过账户余额）
     * 3. 生成交易记录
     * 4. 返回存取款操作结果
     * */
    @PostMapping("/accountin")
    public JsonResult accountin(@RequestBody RequestAccountInAndOut requestAccountInAndOut) {
        String accountname = requestAccountInAndOut.getAccount().getAccountname();
        int id = accountService.getid(accountname);
        String pwd = accountService.getpwd(accountname);
        if (requestAccountInAndOut.getAccount().getPassword().equals(pwd)) {
            BigDecimal moneyin = requestAccountInAndOut.getMoney();
            BigDecimal balance = accountService.getBalance(requestAccountInAndOut.getAccount().getAccountname());
            BigDecimal newbalance = balance.add(moneyin);
            accountService.accountchange(newbalance,accountname);
            Transrecord transrecord = new Transrecord();
            transrecord.setAccountid(id);
            transrecord.setAccountname(accountname);
            transrecord.setOtherid(id);
            transrecord.setOthername(accountname);
            transrecord.setMoney(moneyin);
            Date currentDate = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            String formatDate = format.format(currentDate);
            transrecord.setTransdate(formatDate);
            transrecord.setTranstypeid(0);
            transrecordService.saveRecord(transrecord);
            return new JsonResult(true, "存款成功！");
        }else {
            return new JsonResult(false,"存款失败，请重新操作");
        }
    }

    /* 若前端返回操作类型，取款代码可与存款合并 */
    @PostMapping("/accountout")
    public JsonResult accountout(@RequestBody RequestAccountInAndOut requestAccountInAndOut) {
        String accountname = requestAccountInAndOut.getAccount().getAccountname();
        String pwd = accountService.getpwd(accountname);
        int id = accountService.getid(accountname);
        if (requestAccountInAndOut.getAccount().getPassword().equals(pwd)) {
            BigDecimal moneyout = requestAccountInAndOut.getMoney();
            BigDecimal balance = accountService.getBalance(requestAccountInAndOut.getAccount().getAccountname());
            BigDecimal newbalance = balance.subtract(moneyout);
            if (newbalance.min(BigDecimal.valueOf(0.00))!=newbalance){
            accountService.accountchange(newbalance,accountname);
            Transrecord transrecord = new Transrecord();
            transrecord.setAccountid(id);
            transrecord.setAccountname(accountname);
            transrecord.setOtherid(id);
            transrecord.setOthername(accountname);
            transrecord.setMoney(moneyout);
            Date currentDate = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            String formatDate = format.format(currentDate);
            transrecord.setTransdate(formatDate);
            transrecord.setTranstypeid(1);
            transrecordService.saveRecord(transrecord);
            return new JsonResult(true, "取款成功！");
            }else {
                return new JsonResult(false,"余额不足，取款失败");
            }
        }else {
            return new JsonResult(false,"取款失败，请重新操作");
        }
    }

}
